package com.example.javapracticaltraining.controller;

import com.example.javapracticaltraining.entity.R;
import com.example.javapracticaltraining.entity.pojo.AiHealthReport;
import com.example.javapracticaltraining.entity.pojo.Elderly;
import com.example.javapracticaltraining.entity.vo.response.AiHealthReportVO;
import com.example.javapracticaltraining.scheduler.HealthReportScheduler;
import com.example.javapracticaltraining.service.AiHealthReportService;
import com.example.javapracticaltraining.service.ElderlyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Tag(name = "AI健康报告", description = "提供AI健康报告查询功能")
@RestController
@RequestMapping("/ai/healthreports")
public class AiHealthReportController {

    private static final Logger logger = LoggerFactory.getLogger(AiHealthReportController.class);

    @Autowired
    private AiHealthReportService aiHealthReportService;

    @Autowired
    private ElderlyService elderlyService;

    @Autowired
    private HealthReportScheduler healthReportScheduler;

    @Operation(summary = "获取健康报告列表", description = "获取所有健康报告或按类型筛选")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "返回健康报告列表")
    })
    @GetMapping("/list")
    public R<List<AiHealthReportVO>> getHealthReports(
            @Parameter(description = "报告类型：daily(每日)、weekly(每周)、monthly(每月)，不传则返回所有类型") 
            @RequestParam(required = false) String reportType) {

        List<AiHealthReport> reports;
        if (reportType != null && !reportType.isEmpty()) {
            reports = aiHealthReportService.getReportsByType(reportType);
        } else {
            reports = aiHealthReportService.list();
        }

        return R.success(convertToVOList(reports));
    }

    @Operation(summary = "获取老人健康报告", description = "根据老人ID获取健康报告，可按类型筛选")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "返回老人健康报告列表")
    })
    @GetMapping("/elderly/{elderlyId}")
    public R<List<AiHealthReportVO>> getElderlyHealthReports(
            @Parameter(description = "老人ID", required = true) 
            @PathVariable Integer elderlyId,
            @Parameter(description = "报告类型：daily(每日)、weekly(每周)、monthly(每月)，不传则返回所有类型") 
            @RequestParam(required = false) String reportType) {

        List<AiHealthReport> reports;
        if (reportType != null && !reportType.isEmpty()) {
            reports = aiHealthReportService.getReportsByElderlyIdAndType(elderlyId, reportType);
        } else {
            reports = aiHealthReportService.getReportsByElderlyId(elderlyId);
        }

        return R.success(convertToVOList(reports));
    }

    @Operation(summary = "获取健康报告详情", description = "根据报告ID获取健康报告详情")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "返回健康报告详情"),
        @ApiResponse(responseCode = "404", description = "未找到该健康报告")
    })
    @GetMapping("/report/{reportId}")
    public R<AiHealthReportVO> getHealthReportById(
            @Parameter(description = "报告ID", required = true) 
            @PathVariable Integer reportId) {

        AiHealthReport report = aiHealthReportService.getById(reportId);
        if (report == null) {
            return R.failure(404, "未找到该健康报告");
        }

        return R.success(convertToVO(report));
    }

    /**
     * 将AiHealthReport实体转换为AiHealthReportVO
     */
    private AiHealthReportVO convertToVO(AiHealthReport report) {
        AiHealthReportVO vo = new AiHealthReportVO();
        BeanUtils.copyProperties(report, vo);

        // 设置老人姓名
        if (report.getElderlyId() != null) {
            Elderly elderly = elderlyService.getById(report.getElderlyId());
            if (elderly != null) {
                vo.setElderlyName(elderly.getName());
            }
        }

        return vo;
    }

    /**
     * 将AiHealthReport实体列表转换为AiHealthReportVO列表
     */
    private List<AiHealthReportVO> convertToVOList(List<AiHealthReport> reports) {
        List<AiHealthReportVO> voList = new ArrayList<>();
        for (AiHealthReport report : reports) {
            voList.add(convertToVO(report));
        }
        return voList;
    }

    @Operation(summary = "测试生成健康报告", description = "直接调用日报、周报、月报的自动生成方法")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "报告生成成功")
    })
    @GetMapping("/generate")
    public R<String> generateHealthReports(
            @Parameter(description = "报告类型：daily(每日)、weekly(每周)、monthly(每月)、all(全部)，默认为all") 
            @RequestParam(required = false, defaultValue = "all") String reportType) {

        logger.info("开始测试生成健康报告，类型: " + reportType);

        try {
            switch (reportType.toLowerCase()) {
                case "daily" -> {
                    healthReportScheduler.generateDailyReports();
                    return R.success("每日健康报告生成成功");
                }
                case "weekly" -> {
                    healthReportScheduler.generateWeeklyReports();
                    return R.success("每周健康报告生成成功");
                }
                case "monthly" -> {
                    healthReportScheduler.generateMonthlyReports();
                    return R.success("每月健康报告生成成功");
                }
                case "all" -> {
                    healthReportScheduler.generateDailyReports();
                    healthReportScheduler.generateWeeklyReports();
                    healthReportScheduler.generateMonthlyReports();
                    return R.success("所有类型健康报告生成成功");
                }
                default -> {
                    return R.failure(400, "无效的报告类型: " + reportType + "，有效类型为: daily, weekly, monthly, all");
                }
            }
        } catch (Exception e) {
            logger.error("生成健康报告失败", e);
            return R.failure(500, "生成健康报告失败: " + e.getMessage());
        }
    }
}
